package org.geektimes.projects.user.web.controller;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.orm.jpa.DelegatingEntityManager;
import org.geektimes.projects.user.repository.DatabaseUserRepository;
import org.geektimes.projects.user.repository.UserRepository;
import org.geektimes.projects.user.validator.bean.validation.DelegatingValidator;
import org.geektimes.web.mvc.annotation.Controller;
import org.geektimes.web.mvc.context.ComponentContext;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;

import javax.annotation.Resource;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author 曾虎
 * @Date 2021/3/2
 */
@Controller
@Path("/user")
public class UserController {

    UserRepository userRepository=new DatabaseUserRepository();

    @Resource(name="bean/EntityManager")
    DelegatingEntityManager dbConnectionManager;

    @Resource(name = "bean/Validator")
    DelegatingValidator delegatingValidator;

    @GET
    @Path("/index")
    public String index(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        return "index.jsp";
    }

    @GET
    @Path("/goregister")
    public String goregister(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        ComponentContext componentContext = ComponentContext.getInstance();
        Config config=componentContext.getConfig();
        //从配置中获取信息
        System.out.println("application.name:"+config.getValue("application.name",String.class));
        System.out.println("application.port:"+config.getValue("application.port",Integer.class));

        String sql = "select * from users ";
        Query query= dbConnectionManager.createNativeQuery(sql);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> users = query.getResultList();
        for (int i = 0; i < users.size(); i++) {
            //System.out.println(users.get(i));
        }
        return "register.jsp";
    }

    @POST
    @Path("/register")
    public String register(HttpServletRequest request, HttpServletResponse response){
        User user=new User();
        user.setEmail(request.getParameter("email"));
        user.setName(request.getParameter("name"));
        user.setPassword(request.getParameter("password"));
        user.setPhoneNumber(request.getParameter("phone"));

        // 校验结果
        Set<ConstraintViolation<User>> violations = delegatingValidator.validate(user);
        List<String> message = new ArrayList<String>();
        violations.forEach(c -> {
            System.out.println(c.getMessage());
            message.add(c.getMessage());
        });
        if(message.size()==0){
            EntityTransaction transaction = dbConnectionManager.getTransaction();
            transaction.begin();
            dbConnectionManager.persist(user);
            transaction.commit();
            user=dbConnectionManager.merge(user);
            if(user.getId()>0){
                return "success.jsp";
            }else{
                return "register.jsp";
            }
        }
        request.setAttribute("message",message);
        return "register.jsp";
    }
}
